<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 价格预警业务逻辑
 */
class PriceAlert extends LogicBase
{
    /**
     * 获取价格预警数据搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 商品ID搜索
        !empty($data['product_id']) && $where['product_id'] = $data['product_id'];
        
        // 状态搜索（0-未触发，1-已触发，2-已取消）
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 预警类型搜索（1-降价预警，2-涨价预警）
        !empty($data['alert_type']) && $where['alert_type'] = $data['alert_type'];
        
        // 价格范围搜索
        if (isset($data['min_price']) && $data['min_price'] !== '') {
            $where['target_price'] = ['>=', $data['min_price']];
        }
        if (isset($data['max_price']) && $data['max_price'] !== '') {
            if (isset($where['target_price'])) {
                $where['target_price'] = ['between', [$data['min_price'], $data['max_price']]];
            } else {
                $where['target_price'] = ['<=', $data['max_price']];
            }
        }
        
        // 搜索条件：商品名称
        !empty($data['search_data']) && $where['product_name'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 设置价格预警
     */
    public function setPriceAlert($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        $alertPrice = $data['alert_price'] ?? 0;
        $alertType = $data['alert_type'] ?? 'lower'; // lower: 低于, higher: 高于
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        if (!$alertPrice || $alertPrice <= 0) {
            return [RESULT_ERROR, '预警价格必须大于0'];
        }
        
        // 检查商品是否存在
        $product = $this->modelProduct->getInfo(['id' => $productId, 'product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE]);
        if (!$product) {
            return [RESULT_ERROR, '商品不存在'];
        }
        
        // 检查用户是否关注了该商品
        $follow = $this->modelUserFollow->getInfo(['user_id' => $userId, 'product_id' => $productId]);
        if (!$follow) {
            return [RESULT_ERROR, '请先关注该商品'];
        }
        
        // 检查是否已经设置过预警
        $existAlert = $this->modelPriceAlert->getInfo([
            'user_id' => $userId,
            'product_id' => $productId,
            'status' => 1
        ]);
        
        $alertData = [
            'user_id' => $userId,
            'product_id' => $productId,
            'alert_price' => $alertPrice,
            'alert_type' => $alertType,
            'current_price' => $product['price'],
            'status' => 1,
            'update_time' => time()
        ];
        
        if ($existAlert) {
            // 更新现有预警
            $result = $this->modelPriceAlert->updateInfo(['id' => $existAlert['id']], $alertData);
            $message = '价格预警更新成功';
        } else {
            // 创建新预警
            $alertData['create_time'] = time();
            $result = $this->modelPriceAlert->insertGetId($alertData);
            $message = '价格预警设置成功';
        }
        
        return $result ? [RESULT_SUCCESS, $message] : [RESULT_ERROR, '设置失败'];
    }
    
    /**
     * 获取用户的价格预警列表
     */
    public function getUserAlerts($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 20;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        $list = $this->modelPriceAlert->getList([
            'user_id' => $userId,
            'status' => 1
        ], true, 'create_time desc', [
            'list_rows' => $limit,
            'page' => $page
        ]);
        
        if ($list && !empty($list)) {
            // 获取商品信息
            $productIds = array_column($list, 'product_id');
            $products = $this->modelProduct->getList(['id' => ['in', $productIds]], true, '', false);
            
            // 建立商品ID映射
            $productMap = [];
            foreach ($products as $product) {
                $productMap[$product['id']] = $product;
            }
            
            // 合并商品信息
            foreach ($list as $key => $item) {
                $product = $productMap[$item['product_id']] ?? null;
                if ($product) {
                    $item['product_name'] = $product['name'];
                    $item['product_image'] = $product['image'];
                    $item['current_price'] = $product['price'];
                    
                    // 判断是否触发预警
                    $item['is_triggered'] = $this->checkAlertTriggered($item, $product['price']);
                }
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
        }
        
        return [RESULT_SUCCESS, '获取预警列表成功', $list];
    }
    
    /**
     * 删除价格预警
     */
    public function removeAlert($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $alertId = $data['alert_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        $where = ['user_id' => $userId];
        if ($alertId) {
            $where['id'] = $alertId;
        } elseif ($productId) {
            $where['product_id'] = $productId;
        } else {
            return [RESULT_ERROR, '预警ID或商品ID不能为空'];
        }
        
        $result = $this->modelPriceAlert->deleteInfo($where);
        
        return $result ? [RESULT_SUCCESS, '删除预警成功'] : [RESULT_ERROR, '删除失败'];
    }
    
    /**
     * 检查价格预警（定时任务调用）
     */
    public function checkPriceAlerts()
    {
        // 获取所有有效的价格预警
        $alerts = $this->modelPriceAlert->getList(['status' => 1], true, '', false);
        
        $triggeredCount = 0;
        $notificationData = [];
        
        foreach ($alerts as $alert) {
            // 获取商品当前价格
            $product = $this->modelProduct->getInfo(['id' => $alert['product_id']]);
            if (!$product) {
                continue;
            }
            
            $currentPrice = $product['price'];
            $isTriggered = $this->checkAlertTriggered($alert, $currentPrice);
            
            if ($isTriggered) {
                // 发送通知
                $notificationData[] = [
                    'user_id' => $alert['user_id'],
                    'product_id' => $alert['product_id'],
                    'product_name' => $product['name'],
                    'alert_price' => $alert['alert_price'],
                    'current_price' => $currentPrice,
                    'alert_type' => $alert['alert_type']
                ];
                
                // 更新预警状态为已触发
                $this->modelPriceAlert->updateInfo(['id' => $alert['id']], [
                    'status' => 2, // 已触发
                    'triggered_time' => time(),
                    'triggered_price' => $currentPrice,
                    'update_time' => time()
                ]);
                
                $triggeredCount++;
            }
        }
        
        // 批量发送通知
        if (!empty($notificationData)) {
            $this->sendPriceAlertNotifications($notificationData);
        }
        
        return [RESULT_SUCCESS, "检查完成，触发{$triggeredCount}个价格预警"];
    }
    
    /**
     * 检查预警是否触发
     */
    private function checkAlertTriggered($alert, $currentPrice)
    {
        if ($alert['alert_type'] == 'lower') {
            // 价格低于预警价格
            return $currentPrice <= $alert['alert_price'];
        } elseif ($alert['alert_type'] == 'higher') {
            // 价格高于预警价格
            return $currentPrice >= $alert['alert_price'];
        }
        
        return false;
    }
    
    /**
     * 发送价格预警通知
     */
    private function sendPriceAlertNotifications($notificationData)
    {
        foreach ($notificationData as $data) {
            try {
                $alertTypeText = $data['alert_type'] == 'lower' ? '低于' : '高于';
                $content = "您关注的商品「{$data['product_name']}」价格已{$alertTypeText}预警价格！\n";
                $content .= "预警价格：¥{$data['alert_price']}\n";
                $content .= "当前价格：¥{$data['current_price']}";
                
                // 发送站内消息
                $this->modelMessage->insertGetId([
                    'user_id' => $data['user_id'],
                    'type' => 'price_alert',
                    'title' => '价格预警提醒',
                    'content' => $content,
                    'is_read' => 0,
                    'create_time' => time(),
                    'update_time' => time()
                ]);
                
                // TODO: 可以在这里添加微信模板消息推送
                
            } catch (\Exception $e) {
                \think\facade\Log::error('发送价格预警通知失败：' . $e->getMessage());
            }
        }
    }
}